import { useState } from 'react';
import { verifyPhone } from '@/utils/utils';
import { View, Text, Switch, Picker } from '@tarojs/components';
import { AtButton, AtForm, AtInput } from 'taro-ui';
import { addAddressInfo, editAddressInfo } from '@/service/apis/mine';
import Taro, { useDidShow } from '@tarojs/taro';
import './style.scss';

const INPUT_TYPE = {
  NAME: 'name', // 姓名
  MOBILE: 'mobile', // 电话
  REGION: 'region', //  地区
  ADDRESS: 'address',
  SET_DEFAULT: 'setDefault',
};

/**
 * 添加用户地址
 */
const AddAddress = () => {
  const [formValue, setFormValue] = useState<any>({
    name: '',
    region: [],
    address: '',
    mobile: '',
    is_default: false,
  });
  const onSubmit = async () => {
    const { name, region, address, mobile, is_default, id } = formValue;

    if (!name || !region.length || !address || !mobile) {
      Taro.showToast({
        title: '请输入完整信息',
        icon: 'none',
      });
      return;
    }
    if (!verifyPhone(mobile)) {
      Taro.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      });
      return;
    }
    try {
      if (id) {
        await editAddressInfo({
          name,
          province_id: region[0],
          city_id: region[1],
          area_id: region[2],
          address,
          mobile,
          address_id: id,
          is_default: is_default ? 1 : 0,
        });
        Taro.showToast({
          title: '地址编辑成功',
          icon: 'success',
          duration: 2000,
        });
      } else {
        await addAddressInfo({
          name,
          province_id: region[0],
          city_id: region[1],
          area_id: region[2],
          address,
          mobile,
          is_default: is_default ? 1 : 0,
        });
        Taro.showToast({
          title: '地址新增成功',
          icon: 'success',
          duration: 2000,
        });
      }
      Taro.navigateBack();
    } catch (error) {
      console.error(error);
      Taro.showToast({
        title: '地址编辑失败',
        icon: 'error',
        duration: 2000,
      });
    }
  };
  const handleChange = (type) => {
    return (val) => {
      console.log('val', type, val);
      switch (type) {
        case INPUT_TYPE.REGION:
          setFormValue({
            ...formValue,
            region: val.detail.value,
          });
          break;
        case INPUT_TYPE.NAME:
          setFormValue({
            ...formValue,
            name: val,
          });
          break;
        case INPUT_TYPE.ADDRESS:
          setFormValue({
            ...formValue,
            address: val,
          });
          break;
        case INPUT_TYPE.MOBILE:
          setFormValue({
            ...formValue,
            mobile: val,
          });
          break;
        case INPUT_TYPE.SET_DEFAULT:
          setFormValue({
            ...formValue,
            is_default: val.detail.value,
          });
          break;
      }
    };
  };
  useDidShow(() => {
    const $instance = Taro.getCurrentInstance();
    const { addressInfo = '' } = $instance?.router?.params || {};
    if (addressInfo !== 'undefined') {
      const _addressInfo = JSON.parse(addressInfo);
      const { province_id, city_id, area_id } = _addressInfo;
      setFormValue({
        ..._addressInfo,
        region: [province_id, city_id, area_id],
      });
    }
  });

  return (
    <AtForm onSubmit={onSubmit} className="add-address-container page-container">
      <View className="input-text-wrap">
        <AtInput
          name="name"
          title="联系人"
          type="text"
          placeholder="姓名"
          value={formValue.name}
          onChange={handleChange(INPUT_TYPE.NAME)}
        />
        <AtInput
          name="mobile"
          title="联系电话"
          type="text"
          placeholder="手机或固定电话"
          value={formValue.mobile}
          onChange={handleChange(INPUT_TYPE.MOBILE)}
        />
        <View className="address-section">
          <Text className="form-title">省市区</Text>
          <View>
            <Picker
              mode="region"
              value={formValue.region}
              onChange={handleChange(INPUT_TYPE.REGION)}
            >
              {/* <View className="picker">请选择{formValue.region}</View> */}
              {formValue.region.length === 0 ? '请选择' : formValue.region}
            </Picker>
          </View>
          <View className="border" />
        </View>
        <AtInput
          name="address"
          title="详细地址"
          type="text"
          placeholder="如街道、楼层、门牌号等"
          value={formValue.address}
          onChange={handleChange(INPUT_TYPE.ADDRESS)}
        />
        {/* <AtInput
          name='number'
          title='门牌号'
          type='text'
          placeholder='门牌号'
          value={formValue.accountNumber}
          onChange={handleChange(INPUT_TYPE.)}
        />
        <AtInput
          name='number'
          title='邮政编码'
          type='text'
          placeholder='邮政编码（选填）'
          value={formValue.accountNumber}
          onChange={handleChange(INPUT_TYPE.ACCOUNT_NUMBER)}
        /> */}
        <View className="address-section">
          <Text className="form-title">设为默认联系人</Text>
          <Switch onChange={handleChange(INPUT_TYPE.SET_DEFAULT)} checked={formValue.is_default} />
        </View>
      </View>

      <AtButton className="submint-btn" onClick={onSubmit}>
        提交
      </AtButton>
    </AtForm>
  );
};
export default AddAddress;
